package com.icesoft.core.common.helper;

import java.util.Collection;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SpringContextUtils implements BeanFactoryPostProcessor {

	private static ConfigurableListableBeanFactory configurableListableBeanFactory;

	public static <T> T getBean(Class<T> clazz) throws BeansException {
		if (configurableListableBeanFactory == null) {
			log.error("configurableListableBeanFactory not init");
			return null;
		}
		
		return configurableListableBeanFactory.getBean(clazz);
	}
	public static <T> Collection<T> getBeans(Class<T> clazz){
		if (configurableListableBeanFactory == null) {
			log.error("configurableListableBeanFactory not init");
			return null;
		}
		return configurableListableBeanFactory.getBeansOfType(clazz).values();
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		if (configurableListableBeanFactory == null) {
			log.error("configurableListableBeanFactory not init");
			return null;
		}
		return (T) configurableListableBeanFactory.getBean(name);
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		configurableListableBeanFactory = beanFactory;
	}

}